#include <gtest/gtest.h>
#include "Thread/TaskExecutor.h"
#include <chrono>
#include <atomic>
#include <vector>

using namespace toolkit;
using namespace std::chrono_literals;

// 测试 ThreadLoadCounter 类
TEST(ThreadLoadCounterTest, BasicOperations) {
    ThreadLoadCounter counter;
    
    // 初始负载应为0
    EXPECT_EQ(counter.getLoad(), 0);
    
    // 增加负载
    counter.addLoad();
    EXPECT_EQ(counter.getLoad(), 1);
    
    counter.addLoad();
    EXPECT_EQ(counter.getLoad(), 2);
    
    // 减少负载
    counter.reduceLoad();
    EXPECT_EQ(counter.getLoad(), 1);
    
    counter.reduceLoad();
    EXPECT_EQ(counter.getLoad(), 0);
}

// 测试 TaskCancelableImp 类
TEST(TaskCancelableImpTest, CancelOperation) {
    auto cancelable = std::make_shared<TaskCancelableImp>();
    
    // 初始状态应为未取消
    EXPECT_FALSE(cancelable->isCanceled());
    
    // 取消任务
    cancelable->cancel();
    EXPECT_TRUE(cancelable->isCanceled());
}

// 测试 TaskExecutorImp 类的基本功能
TEST(TaskExecutorImpTest, BasicAsyncExecution) {
    auto executor = std::make_shared<TaskExecutorImp>(2); // 创建2个线程的执行器
    
    std::atomic<int> counter{0};
    std::atomic<bool> task_executed{false};
    
    // 测试异步执行
    auto cancelable = executor->async([&]() {
        counter++;
        task_executed = true;
        std::this_thread::sleep_for(100ms); // 模拟耗时操作
    });
    
    // 等待任务执行完成
    std::this_thread::sleep_for(200ms);
    
    EXPECT_TRUE(task_executed);
    EXPECT_EQ(counter, 1);
}

// 测试任务取消功能
TEST(TaskExecutorImpTest, TaskCancellation) {
    auto executor = std::make_shared<TaskExecutorImp>(1); // 单线程执行器
    
    std::atomic<bool> task_executed{false};
    
    // 提交大量任务以确保队列中有任务
    for (int i = 0; i < 100; i++) {
        executor->async([&]() {
            std::this_thread::sleep_for(10ms);
        });
    }
    
    // 提交一个任务并立即取消
    auto cancelable = executor->async([&]() {
        task_executed = true;
    });
    
    cancelable->cancel();
    
    // 等待一段时间，确保所有任务有机会执行
    std::this_thread::sleep_for(500ms);
    
    // 由于任务可能在取消前已经执行，这个测试可能不稳定
    // 这里我们只是演示取消功能，实际测试中可能需要更复杂的同步机制
    EXPECT_FALSE(task_executed);
}

// 测试优先执行功能
TEST(TaskExecutorImpTest, PriorityExecution) {
    auto executor = std::make_shared<TaskExecutorImp>(1); // 单线程执行器
    
    std::vector<int> execution_order;
    std::mutex mutex;
    
    // 提交10个普通任务
    for (int i = 0; i < 10; i++) {
        executor->async([i, &execution_order, &mutex]() {
            std::lock_guard<std::mutex> lock(mutex);
            execution_order.push_back(i);
            std::this_thread::sleep_for(10ms);
        });
    }
    
    // 提交一个优先任务
    executor->async_first([&execution_order, &mutex]() {
        std::lock_guard<std::mutex> lock(mutex);
        execution_order.push_back(999); // 特殊标记
        std::this_thread::sleep_for(10ms);
    });
    
    // 等待足够长的时间让任务执行
    std::this_thread::sleep_for(200ms);
    
    // 检查优先任务是否在普通任务之前执行
    // 注意：由于第一个任务可能已经开始执行，优先任务可能不是第一个执行的
    // 但它应该在大多数普通任务之前执行
    bool priority_task_found = false;
    int priority_task_position = -1;
    
    {
        std::lock_guard<std::mutex> lock(mutex);
        for (int i = 0; i < execution_order.size(); i++) {
            if (execution_order[i] == 999) {
                priority_task_found = true;
                priority_task_position = i;
                break;
            }
        }
    }
    
    EXPECT_TRUE(priority_task_found);
    // 优先任务应该在前几个位置执行
    EXPECT_LT(priority_task_position, 5);
}

// 测试 TaskExecutorGetterImp 类
TEST(TaskExecutorGetterImpTest, GetExecutor) {
    auto executor = std::make_shared<TaskExecutorImp>(2);
    auto getter = std::make_shared<TaskExecutorGetterImp>(executor);
    
    EXPECT_EQ(getter->getExecutor(), executor);
}

// 测试负载计数
TEST(TaskExecutorImpTest, LoadCounting) {
    auto executor = std::make_shared<TaskExecutorImp>(2);
    
    // 初始负载应为0
    EXPECT_EQ(executor->getLoad(), 0);
    
    std::atomic<bool> task1_running{false};
    std::atomic<bool> task2_running{false};
    std::atomic<bool> can_finish{false};
    
    // 提交两个长时间运行的任务
    auto task1 = executor->async([&]() {
        task1_running = true;
        while (!can_finish) {
            std::this_thread::sleep_for(10ms);
        }
    });
    
    auto task2 = executor->async([&]() {
        task2_running = true;
        while (!can_finish) {
            std::this_thread::sleep_for(10ms);
        }
    });
    
    // 等待任务开始执行
    while (!task1_running || !task2_running) {
        std::this_thread::sleep_for(10ms);
    }
    
    // 检查负载
    EXPECT_EQ(executor->getLoad(), 2);
    
    // 允许任务完成
    can_finish = true;
    
    // 等待任务完成
    std::this_thread::sleep_for(100ms);
    
    // 负载应该回到0
    EXPECT_EQ(executor->getLoad(), 0);
}

// 测试同步执行选项
TEST(TaskExecutorImpTest, SyncExecution) {
    // 创建一个没有线程的执行器，所有任务都会同步执行
    auto executor = std::make_shared<TaskExecutorImp>(0);
    
    std::atomic<bool> task_executed{false};
    
    // 使用may_sync=true提交任务
    executor->async([&]() {
        task_executed = true;
    }, true);
    
    // 任务应该已经同步执行完成
    EXPECT_TRUE(task_executed);
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}